package office.stock.services;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import office.stock.messaging.notifications.NewOfferNotification;
import office.stock.messaging.notifications.OfferClosedNotification;
import office.stock.messaging.notifications.OfferRemovedNotification;
import office.stock.model.Offer;
import office.stock.model.User;
import office.stock.persistance.OfferDAO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Stateless
public class OffersServiceImpl implements OffersService {

    private final static Log log = LogFactory.getLog(OffersServiceImpl.class); 
    
    @EJB
    private OfferDAO offerDAO;
    
    @EJB
    private ImageStorage imageStorage;
    
    @EJB
    private NotificationService notificationService;
    
    @Override
    public List<Offer> getAll() {
	List<Offer> offers = offerDAO.getAllActive();
	return offers;
    }

    @Override
    public void addNewOffer(Offer offer) {
	offerDAO.persist(offer);
	notificationService.notifyUsers(new NewOfferNotification(offer));
    }

    //TODO add proper handling of concurrent buying/removing
    @Override
    public Offer remove(Long id) {
	Offer offer = offerDAO.remove(id);
	log.debug("removed offer " + offer);
	imageStorage.remove(offer.getImageId());
	notificationService.notifyUsers(new OfferRemovedNotification(id));
	return offer;
    }

    @Override
    public void buy(Long offerId, User buyer) {
	Offer offer = offerDAO.getById(offerId);
	offer.setSold(true);
	offer.setNewOwner(buyer);
	offerDAO.update(offer);
	notificationService.notifyUsers(new OfferClosedNotification(offerId, offer.getSeller().getEmail()));
    }
}
